package com.example.yls.demoa;

import android.content.Context;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by yls on 2018/10/8.
 */

public class StuAdapter extends BaseAdapter {

    private Context context;
    private List<Student> stuList;
    private EventListening event;

    public StuAdapter(EventListening event,Context context, List<Student> stuList) {
        this.event = event;
        this.context = context;
        this.stuList = stuList;
    }

    @Override
    public int getCount() {
        return stuList.size();
    }

    @Override
    public Object getItem(int i) {
        return stuList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {

        if(view == null){
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            view = layoutInflater.inflate(R.layout.list_item_stu,
                    viewGroup,false);
            StuItemViewHolder stuItemViewHolder = new StuItemViewHolder();
            stuItemViewHolder.headView = view.findViewById(R.id.stu_img);
            stuItemViewHolder.nameView = view.findViewById(R.id.stu_name);
            stuItemViewHolder.ageView = view.findViewById(R.id.stu_age);
            stuItemViewHolder.delBtn = view.findViewById(R.id.del_btn);
            view.setTag(stuItemViewHolder);
        }
        StuItemViewHolder stuItemViewHolder = (StuItemViewHolder) view.getTag();

        Student student = stuList.get(i);

        stuItemViewHolder.headView.setImageResource(student.getImgId());
        stuItemViewHolder.nameView.setText(student.getName());
        stuItemViewHolder.ageView.setText(String.valueOf(student.getAge()));
        stuItemViewHolder.delBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                event.delete(stuList.get(i));
                Log.d("king","index:"+i);
            }
        });
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                event.edit(stuList.get(i));
            }
        });

        return view;
    }

    public void change(List<Student> search) {
        this.stuList = search;
        this.notifyDataSetChanged();
    }

    public List<Student> getData(){
        return this.stuList;
    }

}

class StuItemViewHolder{
    ImageView headView;
    TextView nameView;
    TextView ageView;
    ImageButton delBtn;
}
